<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @closed="dialogClose">
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="120px">
      <el-form-item label="选择分类" placeholder="请选择商品分类">
        <category-cascade :categoryPath.sync="categoryPath"></category-cascade>
      </el-form-item>
      <el-form-item label="选择品牌" placeholder="请选择商品品牌">
        <brand-select :newBrandId.sync="dataForm.newBrandId"></brand-select>
      </el-form-item>
      <el-form-item label="采购商品" prop="skuId">
        <el-select v-model="dataForm.skuId" placeholder="请选择采购商品" filterable clearable>
          <el-option v-for="sku in skuList" :key="sku.skuId" :label="sku.skuName" :value="sku.skuId"></el-option>
        </el-select>
        <!--<el-input v-model="dataForm.skuId" placeholder="采购商品id"></el-input>-->
      </el-form-item>
      <el-form-item label="采购数量" prop="skuNum">
        <el-input v-model="dataForm.skuNum" placeholder="采购数量"></el-input>
      </el-form-item>
      <el-form-item label="仓库" prop="wareId">
        <el-select v-model="dataForm.wareId" placeholder="请选择仓库" clearable>
          <el-option :label="w.name" :value="w.id" v-for="w in wareList" :key="w.id"></el-option>
        </el-select>
      </el-form-item>
      <!-- [0新建，1已分配，2正在采购，3已完成，4采购失败] -->
      <!-- <el-form-item label="状态" prop="status">
        <el-select v-model="dataForm.status" placeholder="请选择状态" clearable>
          <el-option label="新建" :value="0"></el-option>
          <el-option label="已分配" :value="1"></el-option>
          <el-option label="正在采购" :value="2"></el-option>
          <el-option label="已完成" :value="3"></el-option>
          <el-option label="采购失败" :value="4"></el-option>
        </el-select>
      </el-form-item>-->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import CategoryCascade from "../common/category-cascader";
import BrandSelect from "../common/brand-select";
import PubSub from "pubsub-js";

export default {
  // import引入的组件需要注入到对象中才能使用
  components: {CategoryCascade, BrandSelect},
  data() {
    return {
      catPathSub: null,
      brandIdSub: null,
      visible: false,
      wareList: [],
      skuList: [],
      dataForm: {
        id: 0,
        purchaseId: "",
        skuId: "",
        categoryId: "",
        newBrandId: "",
        // skuName: "",
        skuNum: "",
        skuPrice: "",
        wareId: "",
        status: 0
      },
      categoryPath: [],
      dataRule: {
        categoryId: [
          {required: true, message: "请选择一个分类", trigger: "blur"},
        ],
        brandId: [
          {required: true, message: "请选择一个品牌", trigger: "blur"},
        ],
        skuId: [
          {required: true, message: "采购商品不能为空", trigger: "blur"}
        ],
        skuNum: [
          {required: true, message: "采购数量不能为空", trigger: "blur"}
        ],
        wareId: [{required: true, message: "仓库id不能为空", trigger: "blur"}]
      }
    };
  },
  created() {
    this.getWares();
    this.catPathSub = PubSub.subscribe("catPath", (msg, val) => {
      this.dataForm.categoryId = val[val.length - 1];
      if (this.dataForm.categoryId !== undefined && this.dataForm.categoryId !== 0) {
        this.brandIdSub = PubSub.subscribe("brandId", (msg, val) => {
          this.dataForm.newBrandId = val;
          if (this.dataForm.newBrandId) {
            // console.log("created => ", this.dataForm.categoryId, " and brandId => ", this.dataForm.brandId);
            this.getSkus();
          }
        });
      }
    });

    // this.getSkus();
  },
  updated() {
  },
  watch: {

  },
  methods: {
    // TODO pageSize: 500 后期使用list
    getWares() {
      this.$http({
        url: this.$http.adornUrl("/ware/search"),
        method: "post",
        data: this.$http.adornData({
          pageNum: 1,
          pageSize: 500
        })
      }).then(({data}) => {
        this.wareList = data.page.data;
      });
    },
    getSkus() {
      this.$http({
        url: this.$http.adornUrl("/product/sku-info/filter"),
        method: "post",
        data: this.$http.adornData({
          categoryId: this.dataForm.categoryId,
          brandId: this.dataForm.newBrandId
        })
      }).then(({data}) => {
        this.skuList = data.list;
      });
    },
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/ware/purchase-detail/get/${this.dataForm.id}`
            ),
            method: "get"
          }).then(({data}) => {
            if (data && data.code === 200) {
              this.dataForm.purchaseId = data.detail.purchaseId;
              this.dataForm.skuId = data.detail.skuId;
              this.dataForm.categoryId = data.detail.categoryId;
              this.dataForm.newBrandId = data.detail.brandId;
              this.categoryPath = data.detail.categoryPath;
              this.dataForm.skuNum = data.detail.skuNum;
              this.dataForm.skuPrice = data.detail.skuPrice;
              this.dataForm.wareId = data.detail.wareId;
              this.dataForm.status = data.detail.status;
            }
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/ware/purchase-detail/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              purchaseId: this.dataForm.purchaseId,
              skuId: this.dataForm.skuId,
              brandId: this.dataForm.brandId,
              categoryId: this.dataForm.categoryId,
              skuNum: this.dataForm.skuNum,
              skuPrice: this.dataForm.skuPrice,
              wareId: this.dataForm.wareId,
              status: this.dataForm.status
            })
          }).then(({data}) => {
            if (data && data.code === 200) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    mounted() {
    },
    dialogClose () {
      this.categoryPath = [];
      this.dataForm.newBrandId = "";
    },
    // 生命周期 - 销毁之前
    beforeDestroy() {
      PubSub.unsubscribe(this.catPathSub);
      PubSub.unsubscribe(this.brandIdSub);
    }
  }
};
</script>
